<template>
	<div class="CountDown">
		<p v-if="!isEnd">{{minute}}:{{second}}</p>
        <p v-if="isEnd">{{ endText }}</p>
	</div>
</template>
    
    <script type="text/ecmascript-6">
export default {
	name: "CountDown",
	data() {
		return {
			minutes: 10,
            seconds: 10,
            isEnd: false
		};
	},
	props: {
		countTime: {
			type: Object,
			default: () => {}
        },
        endText: {
            type: String,
            default: '下一步'
        }
	},
	mounted() {
		this.add();
	},
	methods: {
		num: function(n) {
			return n < 10 ? "0" + n : "" + n;
		},
		add: function() {
			var _this = this;
			var time = window.setInterval(function() {
				if (_this.seconds === 0 && _this.minutes !== 0) {
					_this.seconds = 59;
					_this.minutes -= 1;
				} else if (_this.minutes === 0 && _this.seconds === 0) {
					_this.seconds = 0;
                    window.clearInterval(time);
                    _this.isEnd = true
                    _this.$emit('countEnd')
				} else {
					_this.seconds -= 1;
				}
			}, 1000);
		}
	},
	watch: {
		countTime: {
			deep: true,
			immediate: true,
			handler: function(newVal) {
				this.minutes = newVal.minute;
				this.seconds = newVal.second;
			}
		},
		second: {
			handler(newVal) {
				this.num(newVal);
			}
		},
		minute: {
			handler(newVal) {
				this.num(newVal);
			}
		}
	},
	computed: {
		second: function() {
			return this.num(this.seconds);
		},
		minute: function() {
			return this.num(this.minutes);
		}
	}
};
</script>
    
<style lang="scss" scoped>
.CountDown {
    color: #fff;
    font-size: 1.6rem;
}
</style>
